/* --------------------------------------------------------------------	*
 * master_mpi.c															*
 * 																		*
 * Master program for adding the elements of an array using MPI			*
 * --------------------------------------------------------------------	*/
#include <stdio.h>
#include <stdlib.h>
#include <lam/mpi.h>		/* MPI constants and functions				*/
#include "tags.h"			/* tags for different messages				*/
#include "common.h"			/* common constants							*/

int main(int argc, char** argv)
{
	int size, i, sum;
	int items[SIZE];
	int results[NUM_SLAVES];
	MPI_Status status;

	/* initlalize the MPI System				*/
	MPI_Init(&argc, &argv);

	/* check for proper number of processes		*/
	MPI_Comm_size(MPI_COMM_WORLD, &size);

	if(size != 5)
	{
		fprintf(stderr, "Error: Need exactly five processes.\n");
		MPI_Finalize();
		exit(EXIT_FAILURE);
	}

	/* initialize the `items' array				*/
	for(i = 0; i < SIZE; i++)
		items[i] = i;

	/* distribute the data among the slaves		*/
	for(i = 0; i < NUM_SLAVES; i++)
		MPI_Send(items + i*DATA_SIZE, DATA_SIZE, MPI_INT, i + 1,
				 MSG_DATA, MPI_COMM_WORLD);

	/* collect the results from the slaves		*/
	for(i = 0; i < NUM_SLAVES; i++)
	{
		int result;
		
		MPI_Recv(&result, 1, MPI_INT, MPI_ANY_SOURCE, MSG_RESULT,
				 MPI_COMM_WORLD, &status);
		results[status.MPI_SOURCE - 1] = result;
	}

	/* find the final answer					*/
	sum = 0;
	for(i = 0; i < NUM_SLAVES; i++)
		sum = sum + results[i];

	printf("The sum is %d\n", sum);

	/* clean up and exit the MPI system			*/
	MPI_Finalize();

	exit(EXIT_SUCCESS);
} /* and main() */

/* end master_mpi.c	*/
